package com.iss.yunpan.service.impl;

import com.iss.yunpan.dao.FileDao;
import com.iss.yunpan.entity.FileContent;
import com.iss.yunpan.entity.Users;
import com.iss.yunpan.service.FileService;
import com.obs.services.ObsClient;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.ObsObject;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service//代表业务逻辑，能够帮助我们实例化
public class FileServiceImpl implements FileService {
    @Autowired
    private HttpSession session;

    private String endPoint = "obs.cn-north-4.myhuaweicloud.com";
    private String ak = "ZS7UUCRCDF3SDHAPAVR3";
    private String sk = "pstsZ3CZtisNRYxj7yq6BD8ModxQ6OJ1wr9yeBJc";
    private String bucketName = "yunpan5";

    @Autowired//依赖注入
    private FileDao dao;

    @Override
    public List<FileContent> getAllFile(String fileName) {
        return dao.getAllFile(fileName);
    }

    @Override
    public boolean checkFileContent(String fileName, Integer parentId) {
        FileContent cont = dao.getFileContentByFileNameAndParentId(fileName, parentId);//此处方法可能在老师所讲的文件上传内容中
        if (cont != null) {
            return true;
        }
        return false;
    }

    @Override
    public void insertFolder(String fileName, Integer parentId) {
        Users user = (Users) session.getAttribute("users");
        if (user != null && !"".equals(user.getUserId())) {
            FileContent con = new FileContent();
            con.setFileName(fileName);
            con.setParentId(parentId);
            con.setUploadTime(new Date());
            con.setUserId(user.getUserId());
            con.setFileType("文件夹");
            con.setFileAbsolute(fileName);
            dao.insertFile(con);//大写？小写？
// 创建ObsClient实例  //此处方法可能在老师所讲的文件上传内容中
            ObsClient obsClient = new ObsClient(ak, sk, endPoint);//尚未定义
            //来源于pdf 9.5节******************************************************//
            //  final String keySuffixWithSlash = "parent_directory/";
            obsClient.putObject("bucketName", fileName + '/', new ByteArrayInputStream(new byte[0]));//bucketname
//上一行’/‘为自行修改
            //**********************************************//
            // obsClient.putObject(backetName,fileName,input);
        }


    }

    /**
     * 如果文件名相同，更新文件；如果文件名不存在，添加文件
     *
     * @param fileName
     * @param input
     * @param parentId
     */
    @Override
    @Transactional
    public void uploadFile(String fileName, InputStream input, String parentId) throws IOException {
        Users user = (Users) session.getAttribute("users");
        if (user != null && !user.getUserId().equals("")) {
            FileContent con = dao.getFileContentByFileNameAndParentId(fileName, Integer.valueOf(parentId));
            if (con != null) {//存在相同文件名的文件,更新
                con.setFileSize(input.available() + "kb");//新文件大小
                con.setUploadTime(new Date());
                dao.updateFile(con);//更新文件
            } else {//不存在该文件，添加

                FileContent cont = new FileContent();//新建文件
                cont.setFileName(fileName);
                cont.setFileSize(input.available() + "kb");
                cont.setFileAbsolute(fileName);//项目的完整路径
                cont.setFileType(fileName.substring(fileName.lastIndexOf("."), fileName.length()));//截取文件名从。到最后
                cont.setParentId(Integer.valueOf(parentId));//string转int
                cont.setUserId(user.getUserId());//需要从前面的UserId传过来，先固定
                cont.setUploadTime(new Date());

                //创建ObsClient实例
                ObsClient obsClient = new ObsClient(ak, sk, endPoint);
                obsClient.putObject(bucketName, fileName, input);//input本地文件路
                String url = signatureUrl(fileName);
                cont.setUrl(url);
                dao.insertFile(cont);
            }

        }
    }

    /**
     * 获得下载路径
     *
     * @return
     */
    public String signatureUrl(String filename) {
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);//尚未定义
        long expireSeconds = 3600L;
        TemporarySignatureRequest request = new TemporarySignatureRequest();
        request.setBucketName(bucketName);
        request.setObjectKey(filename);

        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        request.setExpires(600000);
        return response.getSignedUrl();
    }
}
